<template>
  <div>
    <PerfectTableComponent
      dialogWidth="1300px"
      :loadTableList="loadTableList"
      :changePageSize="changePageSize"
      :changePage="changePage"
      :removeQueryField="removeQueryField"
      :clearQuery="clearQuery"
      v-model:query="query"
      title="物料库存详情"
      ref="tableRef"
      :queryFormHeaders="queryFormHeaders"
      :table="table"
      :tableColumns="tableColumns"
      :showTableIndex="false"
      :operatorColumnWidth="300"
      :baseUrl="urls.API_URL_BACKSTAGE_WMS_WMSMATERIALINVENTORYDETAIL"
      :showDeleteButton="false"
      :show-edit-button="false"
      v-model:form="form"
      :formInline="true"
      :formHeader="formHeader"
      AddNewButtonText="入库"
      @beforeAddRow="beforeAddRow"
      @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
      @beforeFormSubmit="beforeFormSubmit"
      @afterFormSubmitFailure="afterFormSubmitFailure"
      @dialogClosed="dialogClosed"
      @afterSubmitSuccess="afterSubmitSuccess"
    >
      <!-----------------------------表格查询表单自定义元素----------------------------------------->
      <template #query_form_warehouseId>
        <WmsWarehouseCascadeSelectComponent
          ref="wmsWarehouseCascadeSelectQueryComponentRef"
          v-model:warehouseId="query['warehouseSeat.warehouseArea.warehouse.id']"
          v-model:warehouseAreaId="query['warehouseSeat.warehouseArea.id']"
          v-model:warehouseSeatId="query['warehouseSeat.id']"
        />
      </template>
      <!-----------------------------表格自定义列----------------------------------------->
      <!--所属栏目1-->
      <template #table_column_materialName="scope: any">
        {{ scope.row.materialBatch != null ? scope.row.materialBatch.material.name : '' }}
      </template>
      <template #table_column_materialTypeName="scope: any">
        {{ scope.row.materialBatch != null ? scope.row.materialBatch.material.materialType.name : '' }}
      </template>
      <template #table_column_batchNumber="scope: any">
        {{ scope.row.materialBatch != null ? scope.row.materialBatch.batchNumber : '' }}
      </template>
      <template #table_column_warehouseName="scope: any">
        {{ scope.row.warehouseSeat != null ? scope.row.warehouseSeat.warehouseArea.warehouse.name : '' }}
      </template>
      <template #table_column_warehouseAreaName="scope: any">
        {{ scope.row.warehouseSeat != null ? scope.row.warehouseSeat.warehouseArea.name : '' }}
      </template>
      <template #table_column_warehouseSeatName="scope: any">
        {{ scope.row.warehouseSeat != null ? scope.row.warehouseSeat.name : '' }}
      </template>
      <!-----------------------------表格自定义列（操作列）----------------------------------------->
      <template #table_operator_left="scope">
        <el-button @click="MaterialInventoryRelocationRef.openDialog(scope.row.id)" type="primary" size="small" icon="Promotion" plain
          >移库</el-button
        >
      </template>
      <!--表单提交的自定义内容 -->
      <template #dialog_form_materialBatchId>
        <!-- 物料批次选择框 -->
        <MaterialBatchSelectComponent
          v-model="form['materialBatchId']"
          v-model:materialName="form['materialName']"
          @afterClickSelectButton="tableRef.clearFieldValidation('materialBatchId')"
          @closed="tableRef.fieldValidation('materialBatchId')"
          @afterSelectMaterialBatch="afterSelectMaterialBatch"
        />
      </template>
      <!--库位选择的自定义内容 -->
      <template #dialog_form_warehouseSeatId>
        <WmsWarehouseCascadeSelectComponent
          ref="wmsWarehouseCascadeSelectFormComponentRef"
          v-model:warehouseSeatId="form['warehouseSeatId']"
          @change="tableRef.fieldValidation('warehouseSeatId')"
        />
      </template>
      <!--对话框表单插槽底部，用于补充其他的插槽-->
      <template #dialog_form_bottom>
        <!--物料存储明细-->
        <MaterialInventoryDetailsForm v-model="form.materialInventory!.materialInventoryDetails" @select-seat="assignSeatValueToSeat" />
      </template>
    </PerfectTableComponent>
    <!--物料移库对话框-->
    <MaterialInventoryRelocation ref="MaterialInventoryRelocationRef" />
  </div>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import MaterialBatchSelectComponent from '@/components/wms/MaterialBatchSelectComponent.vue';
import WmsWarehouseCascadeSelectComponent from '@/components/wms/WmsWarehouseCascadeSelectComponent.vue';
import MaterialInventoryDetailsForm from '@/views/page/wms/materialinventorydetail/MaterialInventoryDetailsForm.vue';
import MaterialInventoryRelocation from '@/views/page/wms/materialinventorydetail/MaterialInventoryRelocation.vue';
import { nextTick, onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { MaterialBatch, WmsMaterialInventory, WmsMaterialInventoryDetail } from '@/types/interface/wms_interface';
import Request from '@/api/request/request';
import { useRoute, useRouter } from 'vue-router';

// 导入路由
const router = useRouter(); // 创建路由对象
const route = useRoute();

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_WMS_WMSMATERIALINVENTORYDETAIL,
  true,
  {},
  false
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//获取其他组件传递过来的值==========================================================
//获取物料批次模块传递过来的物料批次id（如果是从库区模块跳转来的）
const materialBatchOfParam: string | undefined = route.query.materialBatchId as string | undefined;
//赋值给query值
if (typeof materialBatchOfParam != 'undefined' && materialBatchOfParam != null && materialBatchOfParam.length > 0) {
  query.value['materialBatch.id'] = materialBatchOfParam;
}
//获取物料库存模块传递过来的物料库存id（如果是从库区模块跳转来的）
const materialInventoryOfParam: string | undefined = route.query.materialInventoryId as string | undefined;
//赋值给query值
if (typeof materialInventoryOfParam != 'undefined' && materialInventoryOfParam != null && materialInventoryOfParam.length > 0) {
  query.value['materialInventory.id'] = materialInventoryOfParam;
}
//执行查询，刷新表格
loadTableList();
//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象1
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<WmsMaterialInventoryDetail>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

//定义库位级联框
const wmsWarehouseCascadeSelectFormComponentRef = ref();

const getMaterialType = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_MATERIALTYPE + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const lockDict = await getDict('锁定状态', 'boolean');
  //定义物料类别选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const typeDict = await getDict('物料类型', 'number');
  //获取物料类别列表
  const materialTypes = await getMaterialType();
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'materialTypeId',
      propAsName: 'material.materialType.id',
      label: '物料类别',
      type: 'selectObject',
      list: materialTypes,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      }
    },
    {
      prop: 'materialBatch.material.name',
      label: '物料名称'
    },
    {
      prop: 'materialBatch.batchNumber',
      label: '物料批号'
    },
    {
      label: '物料类型',
      prop: 'materialBatch.material.type',
      type: 'select',
      list: typeDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      prop: 'materialBatch.id',
      label: '物料批次',
      type: 'selectRemote',
      width: '300px',
      url: urls.API_URL_BACKSTAGE_WMS_WMSMATERIALBATCH,
      queryNameForUrl: 'material.name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{material.name}（批次号：{batchNumber}）',
          labelRegexType: 2
          // label: '{material.name}（|批次号：{batchNumber}）'
          // label: 'material.name|batchNumber'
          // label: '物料：{material.name}'
        }
      }
    },
    {
      prop: 'materialInventory.id',
      label: '物料库存',
      type: 'selectRemote',
      width: '300px',
      url: urls.API_URL_BACKSTAGE_WMS_WMSMATERIALINVENTORY,
      queryNameForUrl: 'material.name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{material.name}（库存：{totalInventory}）',
          labelRegexType: 2
          // label: '{material.name}（|批次号：{batchNumber}）'
          // label: 'material.name|batchNumber'
          // label: '物料：{material.name}'
        }
      }
    },
    {
      prop: 'warehouseId',
      label: '仓库选择',
      propAsNames: ['warehouseSeat.warehouseArea.warehouse.id', 'warehouseSeat.warehouseArea.id', 'warehouseSeat.id'],
      type: 'custom'
    },
    {
      prop: 'isLock',
      label: '是否锁定',
      type: 'select',
      list: lockDict
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '物料名',
      prop: 'materialName',
      type: 'custom',
      width: 200,
      fixed: true
    },
    {
      label: '物料类别',
      prop: 'materialTypeName',
      type: 'custom',
      width: 150,
      fixed: true
    },
    {
      label: '物料批次',
      prop: 'batchNumber',
      type: 'custom',
      width: 100,
      fixed: true
    },
    {
      label: '仓库',
      prop: 'warehouseName',
      type: 'custom',
      width: 100
    },
    {
      label: '库区',
      prop: 'warehouseAreaName',
      type: 'custom',
      width: 100
    },
    {
      label: '库位',
      prop: 'warehouseSeatName',
      type: 'custom',
      width: 100
    },
    {
      label: '库存数量',
      prop: 'inventory',
      width: 130
    },
    {
      label: '锁定数量',
      prop: 'lockQuantity',
      width: 130
    },
    {
      label: '锁定状态',
      prop: 'isLock',
      width: 100,
      type: 'dict',
      dict: lockDict
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      label: '选择存储物料',
      prop: 'materialBatchDiverd',
      type: 'divider'
    },
    {
      label: '物料批次',
      prop: 'materialBatchId',
      type: 'custom',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '生产批次',
      prop: 'batchNumber',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '生产厂家',
      prop: 'manuFacturer',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '已入库数',
      prop: 'storedQuantity',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '当前总库存',
      prop: 'totalInventory',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '库存上限',
      prop: 'inventoryLimit',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '库存下限',
      prop: 'inventoryLower',
      placeholder: ' ',
      disabled: true
    },
    {
      label: '选择存储库位',
      prop: 'seatDivider',
      type: 'divider'
    },
    {
      label: '选择库位',
      prop: 'warehouseSeatId',
      type: 'custom',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '物料数量',
      prop: 'inventory',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '备注',
      prop: 'remark',
      rules: [
        {
          max: 255,
          message: '长度在不能超过255个字符',
          trigger: 'blur'
        }
      ]
    }
  ];
});
//初始化表单信息
const initForm = () => {
  //传入初始值
  form.value = {
    isLock: false,
    materialInventory: {
      materialInventoryDetails: []
    }
  };
};
//在添加行的动作以前
const beforeAddRow = async () => {
  initForm();
};
//添加编辑等表单关闭后触发
const dialogClosed = () => {
  //通过重新赋值，重置物料信息
  initForm();
  //手动清空仓库选择列表
  wmsWarehouseCascadeSelectFormComponentRef.value.reset();
  // delete form.value.materialInventory;
  // delete form.value.materialBatch;
};
//在添加成功后
const afterSubmitSuccess = () => {
  //通过重新赋值，重置物料信息
  initForm();
  //手动清空仓库选择列表
  wmsWarehouseCascadeSelectFormComponentRef.value.reset();
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: WmsMaterialInventoryDetail) => {
  //重新封装表单对象的值
  // if (formEdit.material != null) {
  //   formEdit.materialId = formEdit.material.id;
  //   formEdit.materialName = formEdit.material.name;
  // }
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.warehouseSeatId != null) {
    form.value.warehouseSeat = {
      id: form.value.warehouseSeatId
    };
  }
};
//在表单提交失败后
const afterFormSubmitFailure = () => {
  //因为表单信息大部分都是disabled的，因此在添加失败后要重新将原来获取加载数据。
  initMaterialInfomation();
};
//在选择物料批次后
const afterSelectMaterialBatch = async (materialBatchs: MaterialBatch[]) => {
  //将当前选择的物料批次返回
  if (materialBatchs.length > 0) {
    //获取物料批次
    form.value.materialBatch = materialBatchs[0];
    //根据选择的物料批次生成其他字段信息。
    initMaterialInfomation();
  }
};
//初始化物料信息，根据选择的物料批次生成其他字段信息。
const initMaterialInfomation = async () => {
  //设置物料批次对应信息
  if (form.value.materialBatch) {
    form.value.manuFacturer = form.value.materialBatch.manuFacturer;
    form.value.batchNumber = form.value.materialBatch.batchNumber;
    form.value.productionDate = form.value.materialBatch.productionDate;
    form.value.storedQuantity = form.value.materialBatch.storedQuantity;
    //获取物料对应的物料库存和物料详情
    const materialInventorys = await getMaterialInventorys(form.value.materialBatch.material!.id!);
    if (materialInventorys.length > 0) {
      //虽然返回的是集合，但是物料和物料存储是一对一关系。所以只要取第一个
      form.value.materialInventory = materialInventorys[0];
      //物料库存的上下限
      form.value.inventoryLimit = form.value.materialInventory?.inventoryLimit;
      form.value.inventoryLower = form.value.materialInventory?.inventoryLower;
      form.value.totalInventory = form.value.materialInventory?.totalInventory;
    }
  }
};
//获取对应的物料库存集合
const getMaterialInventorys = async (materialId: string) => {
  let materialInventorys = null;
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_WMS_WMSMATERIALINVENTORY, null, {
    params: { 'material.id': materialId }
  }).get();
  if (resData.success) {
    materialInventorys = resData.data.data;
  }
  return materialInventorys;
};
//在给seat赋值后，回调函数。在已有的库位的“选择”按钮后，直接给此次存入的库位赋值
const assignSeatValueToSeat = async (seatId: string) => {
  tableRef.value.clearFieldValidation('warehouseSeatId');
  wmsWarehouseCascadeSelectFormComponentRef.value.setWarehouseSeat(seatId);
  //手动赋值，目的是解决验证延迟问题。不然要在第二次赋值才会真正验证。
  form.value.warehouseSeatId = seatId;
  tableRef.value.fieldValidation('warehouseSeatId');
};
//==============================移库操作====================================================
const MaterialInventoryRelocationRef = ref();
</script>

<style scoped></style>
